package com.tanx.controller.user;

import com.tanx.dto.user.UserFormDto;
import com.tanx.dto.user.UserListDto;
import com.tanx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;

/**
 * Created by 唐旭 on 2015/7/8.
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/list.htm")
    public String list(UserListDto listDto, Model model) {
        userService.loadUserListDto(listDto);
        model.addAttribute("listDto", listDto);
        return "user/list";
    }

    @RequestMapping("/add.htm")
    public String addForm(String uuid, Model model) {
        UserFormDto formDto = userService.loadUserFormDto(uuid);
        model.addAttribute("formDto", formDto);
        return "user/user_form";
    }

    @RequestMapping(value = "/add.htm", method = RequestMethod.POST)
    public String addSubmit(@Valid @ModelAttribute("formDto") UserFormDto formDto,
                            BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "user/user_form";
        }
        userService.persistUserFormDto(formDto);
        return "redirect:list.htm";
    }

}
